<template>
  <view class="nearby-stores-page">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input">
        <image src="@/img/车联网服务-03车辆维修-02附近门店_slices/搜索.png" class="search-icon"></image>
        <input 
          type="text" 
          placeholder="搜索" 
          class="search-placeholder"
          v-model="searchKeyword"
          @input="onSearchInput"
        />
      </view>
    </view>
    
    <!-- 排序选项 -->
    <view class="sort-section">
      <view class="sort-option" @click="toggleSortDropdown">
        <text class="sort-text">{{currentSortText}}</text>
        <text class="sort-arrow" :class="{ 'rotate': showSortDropdown }">▼</text>
      </view>
      
      <!-- 下拉框 -->
      <view class="sort-dropdown" v-if="showSortDropdown">
        <view 
          class="sort-item" 
          v-for="(item, index) in sortOptions" 
          :key="index"
          @click="selectSort(item)"
          :class="{ 'active': currentSortType === item.type }"
        >
          <text class="sort-item-text">{{item.text}}</text>
          <text class="sort-item-check" v-if="currentSortType === item.type">✓</text>
        </view>
      </view>
    </view>
    
    <!-- 门店列表 -->
    <view class="store-list">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <text class="loading-text">正在加载门店信息...</text>
      </view>
      
      <!-- 门店列表项 -->
      <view 
        v-else
        class="store-item" 
        v-for="(item, index) in filteredAndSortedStoreList" 
        :key="index"
        @click="selectStore(item)"
      >
        <view class="store-thumbnail">
          <image :src="item.image" mode="aspectFill"></image>
        </view>
        
        <view class="store-info">
          <view class="store-header">
            <text class="store-name">{{item.name}}</text>
            <text class="store-distance">{{item.distance}}m</text>
          </view>
          
          <view class="store-rating">
            <view class="stars">
              <text class="star filled" v-for="i in Math.floor(item.rating)" :key="i">★</text>
              <text class="star" v-for="i in (5 - Math.floor(item.rating))" :key="i + Math.floor(item.rating)">★</text>
              <text class="rating-score">{{item.rating}}分</text>
            </view>
<!--            <text class="store-time">{{item.time}}</text> -->
            <text class="store-sales">销量: {{item.sales}}</text>
          </view>
          
          <view class="store-hours">营业时间: {{item.businessHours}}</view>
          <view class="store-address">{{item.address}}</view>
        </view>
      </view>
    </view>
    
    <!-- 底部提示 -->
    <view class="bottom-tip" v-if="!loading">
      <text v-if="filteredAndSortedStoreList.length === 0">
        {{searchKeyword ? '未找到相关门店' : '附近暂无门店'}}
      </text>
      <text v-else>暂无更多</text>
    </view>
	</view>
</template>

<script>
import { maintenanceMerchantApi } from '@/api/index.js';

	export default {
		data() {
			return {
      searchKeyword: '', // 搜索关键词
      showSortDropdown: false, // 是否显示下拉框
      currentSortType: 'comprehensive', // 当前排序类型
      currentSortText: '综合排序', // 当前排序文本
      sortOptions: [
        { type: 'comprehensive', text: '综合排序' },
        { type: 'distance', text: '距离最近' },
        { type: 'rating', text: '评分最高' },
        { type: 'sales', text: '销量最高' }
      ],
      // 门店数据
      storeList: [],
      loading: false,
      longitude: 113.230000, // 默认经纬度
      latitude: 35.250000,   // 默认经纬度
      serviceTypeId: 2 // 汽车保养服务类型ID
    }
  },
  
  computed: {
    // 过滤后的门店列表
    filteredStoreList() {
      if (!this.searchKeyword.trim()) {
        return this.storeList;
      }
      
      const keyword = this.searchKeyword.toLowerCase();
      return this.storeList.filter(store => {
        return store.name.toLowerCase().includes(keyword) ||
               store.address.toLowerCase().includes(keyword) ||
               store.businessHours.toLowerCase().includes(keyword);
      });
    },
    
    // 根据当前排序类型返回排序后的门店列表
    filteredAndSortedStoreList() {
      const list = [...this.filteredStoreList];
      
      switch (this.currentSortType) {
        case 'distance':
          // 按距离排序（近到远）
          return list.sort((a, b) => a.distance - b.distance);
        case 'rating':
          // 按评分排序（高到低）
          return list.sort((a, b) => b.rating - a.rating);
        case 'sales':
          // 按销量排序（高到低）
          return list.sort((a, b) => b.sales - a.sales);
        case 'comprehensive':
        default:
          // 综合排序（距离40% + 评分40% + 销量20%）
          return list.sort((a, b) => {
            const scoreA = this.calculateComprehensiveScore(a);
            const scoreB = this.calculateComprehensiveScore(b);
            return scoreB - scoreA;
          });
      }
    }
  },
  
  onLoad() {
    // 设置页面标题
    uni.setNavigationBarTitle({
      title: '附近门店'
    });
    
    // 获取位置并加载门店数据
    this.initPageData();
  },
  
		methods: {
    // 初始化页面数据
    async initPageData() {
      await this.getCurrentLocation();
      await this.loadStoreData();
    },

    // 获取当前位置
    getCurrentLocation() {
      return new Promise((resolve) => {
        // #ifdef H5
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(
            (position) => {
              this.longitude = position.coords.longitude;
              this.latitude = position.coords.latitude;
              console.log('HTML5定位成功:', this.longitude, this.latitude);
              resolve();
            },
            (error) => {
              console.error('HTML5定位失败:', error);
              console.log('使用默认经纬度:', this.longitude, this.latitude);
              resolve();
            },
            { timeout: 10000, enableHighAccuracy: true }
          );
        } else {
          console.log('浏览器不支持定位，使用默认经纬度');
          resolve();
        }
        // #endif

        // #ifdef MP-WEIXIN
        uni.getLocation({
          type: 'gcj02',
          success: (res) => {
            this.longitude = res.longitude;
            this.latitude = res.latitude;
            console.log('小程序定位成功:', this.longitude, this.latitude);
            resolve();
          },
          fail: (err) => {
            console.error('小程序定位失败:', err);
            console.log('使用默认经纬度:', this.longitude, this.latitude);
            resolve();
          }
        });
        // #endif
      });
    },

    // 加载门店数据
    async loadStoreData() {
      try {
        this.loading = true;
        console.log('开始获取门店数据，当前位置:', this.longitude, this.latitude);
        
        // 首先尝试按服务类型获取门店
        const response = await maintenanceMerchantApi.getMerchantsByServiceType(this.serviceTypeId, {
          longitude: this.longitude,
          latitude: this.latitude
        });
        
        console.log('API响应:', response);
        
        if (response.code === 200 && response.data && response.data.length > 0) {
          this.storeList = response.data.map(merchant => this.formatStoreData(merchant));
          console.log('格式化后的门店列表:', this.storeList);
        } else {
          // 如果按服务类型没有找到，尝试获取附近所有门店
          await this.loadNearbyStores();
        }
      } catch (error) {
        console.error('获取门店数据失败:', error);
        await this.loadNearbyStores();
      } finally {
        this.loading = false;
      }
    },

    // 获取附近所有门店（备用方法）
    async loadNearbyStores() {
      try {
        console.log('尝试获取附近所有门店');
        
        const response = await maintenanceMerchantApi.getNearbyMerchants({
          longitude: this.longitude,
          latitude: this.latitude,
          radius: 50.0
        });
        
        console.log('附近门店API响应:', response);
        
        if (response.code === 200 && response.data && response.data.length > 0) {
          this.storeList = response.data.map(merchant => this.formatStoreData(merchant));
          console.log('获取到的附近门店:', this.storeList);
        } else {
          console.log('附近也没有找到门店');
          uni.showToast({
            title: '附近暂无门店',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取附近门店失败:', error);
        uni.showToast({
          title: '获取门店信息失败',
          icon: 'none'
        });
      }
    },

    // 格式化门店数据
    formatStoreData(merchant) {
      console.log('正在格式化商户数据:', merchant);
      
      const lng = parseFloat(merchant.longitude) || this.longitude;
      const lat = parseFloat(merchant.latitude) || this.latitude;
      
      // 格式化营业时间
      let businessHours = '营业时间未设置';
      if (merchant.startTime && merchant.endTime) {
        businessHours = `周一至周日 ${merchant.startTime}-${merchant.endTime}`;
      } else if (merchant.businessHours) {
        businessHours = merchant.businessHours;
      }
      
      const formattedData = {
        id: merchant.id,
        name: merchant.name || '未知门店',
        distance: this.calculateDistance(lng, lat),
        time: this.calculateTime(lng, lat),
        rating: merchant.rate || 5, // 使用rate字段
        sales: merchant.monthlySales || 0, // 使用后端返回的真实月销量数据
        businessHours: businessHours,
        address: merchant.address || '地址未设置',
        phone: this.generateDefaultPhone(merchant.id),
        longitude: lng,
        latitude: lat,
        image: merchant.image || require("@/img/车辆维修/维修厂1.jpeg"),
        description: merchant.description || '暂无介绍'
      };
      
      console.log('格式化后的数据:', formattedData);
      return formattedData;
    },

    // 计算距离
    calculateDistance(lng, lat) {
      const R = 6371; // 地球半径（公里）
      const dLat = (lat - this.latitude) * Math.PI / 180;
      const dLng = (lng - this.longitude) * Math.PI / 180;
      const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                Math.cos(this.latitude * Math.PI / 180) * Math.cos(lat * Math.PI / 180) *
                Math.sin(dLng/2) * Math.sin(dLng/2);
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
      const distance = R * c * 1000; // 转换为米
      
      return Math.round(distance);
    },

    // 计算预估时间
    calculateTime(lng, lat) {
      const distance = this.calculateDistance(lng, lat);
      
      if (distance < 1000) {
        return Math.max(1, Math.round(distance / 100)) + '分';
      } else {
        return Math.max(1, Math.round(distance / 1000 * 2)) + '分';
      }
    },

    // 生成默认电话号码
    generateDefaultPhone(merchantId) {
      const phoneMap = {
        15: '18893029302', // 伟业汽车保养场(人民路店)
        16: '18893029303', // 速修汽车保养中心  
        17: '18893029304'  // 专业汽车保养连锁店
      };
      
      return phoneMap[merchantId] || `1889302930${merchantId % 10}`;
    },



    // 搜索输入处理
    onSearchInput() {
      // 搜索时关闭下拉框
      this.showSortDropdown = false;
    },
    
    // 计算综合评分
    calculateComprehensiveScore(store) {
      // 距离得分（距离越近得分越高，最大距离设为2000m）
      const distanceScore = Math.max(0, (2000 - store.distance) / 2000);
      
      // 评分得分（5星满分）
      const ratingScore = store.rating / 5;
      
      // 销量得分（假设最大销量为500）
      const salesScore = Math.min(1, store.sales / 500);
      
      // 综合得分：距离40% + 评分40% + 销量20%
      return distanceScore * 0.4 + ratingScore * 0.4 + salesScore * 0.2;
    },
    
    // 切换下拉框显示状态
    toggleSortDropdown() {
      this.showSortDropdown = !this.showSortDropdown;
    },
    
    // 选择排序方式
    selectSort(sortOption) {
      this.currentSortType = sortOption.type;
      this.currentSortText = sortOption.text;
      this.showSortDropdown = false; // 关闭下拉框
    },
    
    selectStore(store) {
      // 跳转到汽车保养门店详情页面
      uni.navigateTo({
        url: `/pages/carMaintenanceDetails/carMaintenanceDetails?storeData=${encodeURIComponent(JSON.stringify(store))}`,
        success: () => {
          console.log('跳转到汽车保养门店详情页面成功');
        },
        fail: (err) => {
          console.error('跳转到汽车保养门店详情页面失败：', err);
          uni.showToast({
            title: '页面跳转失败',
            icon: 'none'
          });
        }
      });
    }
		}
	}
</script>

<style scoped>
.nearby-stores-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 搜索栏样式 */
.search-bar {
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #eee;
}

.search-input {
  display: flex;
  align-items: center;
  background-color: #f8f8f8;
  border-radius: 20rpx;
  padding: 15rpx 20rpx;
}

.search-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 15rpx;
  flex-shrink: 0;
}

.search-placeholder {
  flex: 1;
  font-size: 28rpx;
  color: #999;
}

/* 排序区域样式 */
.sort-section {
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  position: relative;
  z-index: 100;
}

.sort-option {
  padding: 20rpx 30rpx;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.sort-text {
  font-size: 28rpx;
  color: #333;
  margin-right: 10rpx;
}

.sort-arrow {
  font-size: 24rpx;
  color: #999;
  transition: transform 0.3s ease;
}

.sort-arrow.rotate {
  transform: rotate(180deg);
}

/* 下拉框样式 */
.sort-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top: 1rpx solid #eee;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
  z-index: 101;
}

.sort-item {
  padding: 25rpx 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #f5f5f5;
  cursor: pointer;
}

.sort-item:last-child {
  border-bottom: none;
}

.sort-item.active {
  background-color: #f8f8f8;
}

.sort-item-text {
  font-size: 28rpx;
  color: #333;
}

.sort-item-check {
  font-size: 28rpx;
  color: #007AFF;
  font-weight: bold;
}

/* 门店列表样式 */
.store-list {
  padding: 0 30rpx;
}

.store-item {
  background-color: #fff;
  border-radius: 15rpx;
  margin: 20rpx 0;
  padding: 25rpx;
  display: flex;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
}

.store-thumbnail {
  width: 160rpx;
  height: 160rpx;
  border-radius: 10rpx;
  overflow: hidden;
  margin-right: 25rpx;
  flex-shrink: 0;
}

.store-thumbnail image {
  width: 100%;
  height: 100%;
}

.store-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.store-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15rpx;
}

.store-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  line-height: 1.3;
  flex: 1;
  margin-right: 20rpx;
}

.store-distance {
  font-size: 28rpx;
  color: #007AFF;
  font-weight: bold;
}

.store-rating {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}

.stars {
  display: flex;
  margin-right: 15rpx;
}

.star {
  font-size: 24rpx;
  color: #ddd;
  margin-right: 3rpx;
}

.star.filled {
  color: #FFD700;
}

.rating-score {
  font-size: 22rpx;
  color: #666;
  margin-left: 8rpx;
}

.store-time {
  font-size: 24rpx;
  color: #666;
  margin-right: 20rpx;
}

.store-sales {
  font-size: 24rpx;
  color: #666;
}

.store-hours {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.store-address {
  font-size: 26rpx;
  color: #666;
  line-height: 1.4;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 100rpx 0;
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

/* 底部提示样式 */
.bottom-tip {
  text-align: center;
  padding: 40rpx 0;
  color: #999;
  font-size: 26rpx;
}
</style>
